import { Module, HttpException } from '@nestjs/common';
import { UploadFileController } from './../controllers/filesUpload.controller';
import { MulterModule } from '@nestjs/platform-express';
import { AuthorModule } from './authority.module'
// multer是一个node.js中间件，用于处理 multipart/form-data类型的表单数据，主要用于上传文件。
import { diskStorage } from 'multer';

import * as dayjs from 'dayjs';

import { checkDirAndCreate } from '../utils/getFilePath'

import uuidCreate from '../utils/uuidCreate'

const path = require('path')

import { uploadFail } from '../config/resultInfo'

const image = ['gif', 'png', 'jpg', 'jpeg', 'bmp', 'webp'];
const video = ['mp4', 'webm'];
const audio = ['mp3', 'wav', 'ogg'];

@Module({
  imports: [
    // 简易文件上传
    // MulterModule.register({
    //   storage: diskStorage({
    //     // 配置文件上传后的文件夹路径
    //     // destination: './public/uploads',
    //     filename: (req, file, cb) => {
    //       // 在此处自定义保存后的文件名称
    //       const filename = uuidCreate() + path.extname(file.originalname);
    //       return cb(null, filename);
    //     },
    //   }),
    // }),
    MulterModule.register({
      storage: diskStorage({
        // 配置文件上传后的文件夹路径
        destination: (req, file, cb) => {
          // 根据上传的文件类型将图片视频音频和其他类型文件分别存到对应英文文件夹
          const mimeType = file.mimetype.split('/')[1];
          let temp = 'other';
          image.filter(item => item === mimeType).length > 0 ? (temp = 'image') : '';
          video.filter(item => item === mimeType).length > 0 ? (temp = 'video') : '';
          audio.filter(item => item === mimeType).length > 0 ? (temp = 'audio') : '';
          const filePath = `public/uploads/${temp}/${dayjs().format('YYYYMMDD')}`;
          checkDirAndCreate(filePath); // 判断文件夹是否存在，不存在则自动生成
          return cb(null, `./${filePath}`);
        },
        filename: (req, file, cb) => {
          // 在此处自定义保存后的文件名称
          const filename = uuidCreate() + path.extname(file.originalname);
          return cb(null, filename);
        },
      }),
      // 文件过滤
      fileFilter(req, file, cb) {
        const mimeType = file.mimetype.split('/')[1].toLowerCase();
        let temp = 'other';
        image.filter(item => item === mimeType).length > 0 ? (temp = 'image') : '';
        video.filter(item => item === mimeType).length > 0 ? (temp = 'video') : '';
        audio.filter(item => item === mimeType).length > 0 ? (temp = 'audio') : '';
        if (temp === 'other') {
          return cb(new HttpException(uploadFail.message, uploadFail.statusCode), false);
        }
        return cb(null, true);
      },
    }),
    AuthorModule
  ],
  controllers: [UploadFileController],
  providers: [],
})
export class UpLoadFileModule { }